<template>
  <div>
    <el-card>
      <!-- 筛选区域 -->
      <el-row type="flex" justify="start">
        <el-col :span="6">

          <el-input v-model="filterFrame" style="width: 240px" placeholder="输入维护项目" />

        </el-col>
        <el-col :span="13" style="flex: auto">
          <el-button id="filter-button" type="primary" @click="filterData">筛选</el-button>
          <el-button id="reset-button" type="default" @click="resetFilter">重置</el-button>
<!--          FIXME：添加计划异常-->
          <el-button type="primary" icon="Plus" @click="addPlanDialogVisible=true">添加计划</el-button>
          <AddMaintainPlan :visible="addPlanDialogVisible" @closeDialog2f="closeAddPlanDialog" @freshApps2f="getMaintenancePlanTableData"/>
          <!-- excel导入 -->
          <el-upload
              action="/"
              :http-request="customRequest"
              accept=".xls, .xlsx"
              :on-success="handleImportSuccess"
              :limit="1"
              :show-file-list="false"
              style="display: inline-flex;margin-left: 12px;"
          >
            <el-button type="primary">导入Excel</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <div style="height: 60vh">
        <el-skeleton :loading="loading" animated>
          <el-table :data="paginatedData" border height="100%" style="width: 100%; margin-top:20px">
            <el-table-column prop="dataSeq" label="计划序号" />
            <el-table-column prop="startTime" label="维护日期" />
            <el-table-column prop="mainteItem" label="维护项目" />
            <el-table-column prop="mainteEssentials" label="维护要领" />

            <el-table-column align="center" label="操作">
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                  编辑
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination
              :total="total"
              :current-page.sync="searchForm.current"
              :total-pages="totalPages"
              @update:currentPage="handlePageChange"
          />
        </div>
      </template>
      <UpdMaintainPlan :visible="updMaintainPlanDialogVisible"
                       :id="updMaintainPlanSeq"
                       @closeDialog2f="closeUpdMaintainPlandialog"
                       @freshMaintainPlans2f="getMaintenancePlanTableData"/>
    </el-card>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from "vue";
import { useRouter } from 'vue-router'
import mpApi from '@/api/maintenancePlan'
import Pagination from '@/components/Table/Pagination'
import { ElMessage, ElMessageBox } from 'element-plus';
import UpdMaintainPlan from '@/views/MaintenanceManagement/UpdMaintainPlan';
import AddMaintainPlan from '@/views/MaintenanceManagement/AddMaintainPlan';

const router = useRouter();
// Dom 挂载之后
onMounted(() => {
  getMaintenancePlanTableData();
})
//数据
const allTableData = ref([]);//接收后端全部结果
const tableData = ref([]);
const total = computed(() => tableData.value.length);//总记录条数
const totalPages = ref(1);//总页数
// 监听 allTableData 的变化，并同步更新 tableData
watch(allTableData, (newData) => {
  tableData.value = [...newData];
});

watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
})

const handlePageChange = (page) => {
  searchForm.current = page;
};
//条件筛选
const filterFrame = ref('')

//搜索条件
const searchForm = reactive({
  current: 1,
  size: 10,
})

// 获取维修计划列表
const getMaintenancePlanTableData = async () => {
  const res = await mpApi.getMaintenancePlanData({size: null, current: null});//查询全部
  if (res.data.status) {
    //用all前缀来接收保存
    allTableData.value = res.data.data;
  } else {
    ElMessage.error("获取后端数据失败");
    console.log(res.data.message);
  }
}

//分页监听
// 计算当前页需要显示的数据
const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});

//条件筛选数据
const filterData = () => {
  if (filterFrame.value.trim()) {
    const pattern = filterFrame.value.trim();
    tableData.value = allTableData.value.filter(item => {
      return item.mainteItem.includes(pattern);
    });
  }
}
//重置条件筛选
const resetFilter = () => {
  filterFrame.value = '';
  tableData.value = [...allTableData.value];
}

//加载loading页面
const loading = ref(true);
watch(
    () => paginatedData.value,
    (newValue) => {
      loading.value = !(newValue && newValue.length > 0);
    },
    //配置项确保在组件挂载时，立即执行一次回调，以根据初始值正确设置 loading 的状态
    { immediate: true } // 立即执行一次，以确保初始值状态正确
);
//编辑
const updMaintainPlanSeq = ref('');
const updMaintainPlanDialogVisible = ref(false);
const handleEdit = (index, plan) => {
  updMaintainPlanSeq.value = plan.dataSeq;
  updMaintainPlanDialogVisible.value = true;
}
const closeUpdMaintainPlandialog = (visibility) => {
  updMaintainPlanDialogVisible.value = visibility;
}
//
//删除
const handleDelete = (index, plan) => {
  ElMessageBox.confirm(
      '确定要删除该计划吗?',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const res = await mpApi.deleteSingleMaintenancePlanData({ dataSeq: plan.dataSeq });
    if (res.data.status) {
      ElMessage.success("删除成功")
      getMaintenancePlanTableData();
    } else {
      ElMessage.error("删除失败")
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}
// 添加计划-对话控制
const addPlanDialogVisible = ref(false);
const closeAddPlanDialog = (visibility) => {
  addPlanDialogVisible.value = visibility;
}

const customRequest = async (options) => {
  const { file, onSuccess, onError } = options;
  const formData = new FormData();
  formData.append("file", file);
  try {
    const res = await mpApi.importMaintenancePlan(formData);
    ElMessage.success("文件已上传");
    onSuccess(res.data); // 通知 el-upload 成功
  } catch (error) {
    ElMessage.error("上传失败");
    onError(error); // 通知 el-upload 失败
    console.error("上传失败的错误信息：", error);
  }
};

const handleImportSuccess = () => {
  getMaintenancePlanTableData();
}
</script>

<style scoped lang="scss">
/*筛选-重置按钮*/
.el-button {
  height: 28px;
  color: #FFFFFF;
  font-size: 12px;
  border-radius: 3px
}
#filter-button {
  background-color: $color-filter-button;
}
#reset-button {
  background-color: $color-reset-button;
}
/*card背景、边框*/
.el-card {
  width: 100%;
  background-color: transparent;
  --el-card-border-color: transparent;
}
/*数据表背景*/
:deep(.el-table) {
  color: $color-font-table;//字体颜色
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: transparent;

  // 鼠标悬停时的行样式
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        color: $color-font-table-hover; // 悬停时字体颜色
      }
    }
  }
}
/*日期筛选框背景*/
:deep(.el-input__wrapper) {
  background-color: transparent;
}
</style>